package com.water.bs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.water.bs.pojo.EmailCode;
import com.water.bs.pojo.User;
import com.water.bs.service.EmailService;
import com.water.bs.service.UserService;
import com.water.bs.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private MailUtil mailUtil;
    @RequestMapping("/getUserById")
    public User getUserById(String id){
        User user = userService.getUserById(id);
        return user;
    }

    @RequestMapping("/getUserHead")
    public void getUserHead(@RequestParam("id")String id, final HttpServletResponse response) throws IOException {
        User user = userService.getUserHead(id);
        byte[] data = user.getUserhead();
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputStream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputStream.write(buf, 0, len);
        }
        outputStream.close();
    }

    @RequestMapping("/saveUserHead")
    public JSON saveUserHead(@RequestParam("file") MultipartFile file, @RequestParam("id") String id){
        JSONObject rs = new JSONObject();
        System.out.println(file);
        System.out.println(id);
        Map<String,Object> map = new HashMap<>();
        if (file.isEmpty()){
            rs.put("state","1");
            rs.put("message","上传失败,请重新选择!");
            return rs;
        }
        try {
            InputStream is = file.getInputStream();
            byte[] photoFile = new byte[(int)file.getSize()];
            System.out.println(file.getSize());
            is.read(photoFile);
            map.put("photofile",photoFile);
            map.put("id",id);
            int i = userService.saveUserHead(map);
            if (i>0){
                rs.put("state","0");
                rs.put("message","保存成功");
            }else{
                rs.put("state","1");
                rs.put("message","上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rs;

    }

    @RequestMapping("/sysData")
    public JSON sysData(){
        JSONObject rs = new JSONObject();
        List<Map<String, Object>> gendermaps = userService.genderList();
        rs.put("genderList",gendermaps);

        long nowDate = System.currentTimeMillis();
        List<Map<String, Object>> historyGifts = userService.sevenGiftHistory(nowDate);
        rs.put("historyGifts",historyGifts);

        rs.put("changeCount", userService.changeInfoCount().get("value"));
        rs.put("changeTimeCount",userService.changeTimeCount().get("value"));
        rs.put("userCount",userService.userCount().get("value"));
        rs.put("orgCount",userService.orgCount().get("value"));
        return rs;
    }
    @RequestMapping("/userData")
    public JSON userData(@RequestParam("userid") String userid){
        JSONObject rs = new JSONObject();
        System.out.println("用户id数据:"+userid);
        Map<String, Object> userdata = userService.userData(userid);
        rs.put("userdata",userdata);
        return rs;
    }

    @RequestMapping("/forgetPwd")
    public JSON forgetPwd(@RequestBody JSONObject forgetInfo){
        JSONObject rs = new JSONObject();
        String lowEmail = (String)forgetInfo.get("email");
        int i = userService.isEmailRepeat(lowEmail);
        if (i<1){
            rs.put("state","1");
            rs.put("message","此邮箱尚未注册!");
            return rs;
        }
        forgetInfo.put("email",lowEmail.toLowerCase());
        String s = (String) forgetInfo.get("pwd");
        forgetInfo.put("pwd",DigestUtils.md5DigestAsHex(s.getBytes()));
        System.out.println("忘记密码请求"+forgetInfo);
        //忘记密码请求{"code":"1234","pwd":"bbf2dead374654cbb32a917afd236656","email":"694886886@qq.com"}
        EmailCode emailcode = emailService.getEmailCode((String) forgetInfo.get("email"));
        if (emailcode==null ){
            rs.put("state","2");
            rs.put("message","请获取邮箱验证码进行验证!");
            return rs;
        }
        if (emailcode.getCode().equals(forgetInfo.get("code")) && mailUtil.emailCodeAble(emailcode.getSendTime())) { //验证码验证成功(验证码正确并且再有效期)
            int i1 = userService.forgetPwd(forgetInfo);
            if (i1>0){
                rs.put("state","0");
                rs.put("message","操作成功!");
                return rs;
            }else{
                rs.put("state","3");
                rs.put("message","操作失败!");
                return rs;
            }
        }else{
            rs.put("state","4");
            rs.put("message","验证码错误或已失效!");
            return rs;
        }
    }


}
